<template>
  <div>
    <CToolbar
      :fields="fields"
      :search-fields="['name']"
      :visibleButtons="toolbarOptions"
      @filter="handleFilter"
      @search="handleSearch"
      @openAddRecordDialog="handleAddLifecycleStatus"
      style="position: relative; top: 0; left: 0; padding: 8px 0"
    >
      <template #toolbar-right-before>
        <el-input
          v-model="searchName"
          placeholder="输入关键词"
          class="search-input"
          :prefix-icon="Search"
          @change="handleSearch"
          style="margin-right: 6px"
        />
      </template>
    </CToolbar>
    <div class="wbs-tree-container">
      <!-- 批量操作浮层 -->
      <CLBatchOpToolbar
        :show="showCLBatchOpToolbar"
        :selected-count="selectedRecords.length"
        @delete="handleBatchDelete"
      >
        <!--        <button class="batch-btn">修改属性</button>-->
        <!--        <button class="batch-btn">修改类型</button>-->
      </CLBatchOpToolbar>
      <CLTable
        v-loading="loading"
        :fields="fields"
        :initial-data="tableData"
        :line-height="currentLineHeight"
        :more-actions="moreActions"
        :tableConfig="tableConfig"
        :page-query="tableListQuery"
        @pagerChange="pagerChange"
        @node-selected="handleNodeSelected"
        @onMoreAction="handleMoreAction"
        @show:records="handleShowRecords"
      >
      </CLTable>
      <!-- 字段配置悬浮层 -->
      <FieldConfigPopup
        :fields="currentFields"
        :position="fieldConfigPosition"
        :visible="showFieldConfig"
        @close="showFieldConfig = false"
        @fieldsChange="handleFieldsChange"
      />
    </div>

    <CDialog
      :title="operate === 'create' ? '新增生命周期状态' : '编辑生命周期状态'"
      v-model="dialogVisible"
      @handleDialogOk="handleCreateOrEdit"
      :fields="dialogFields"
      :nodeData="nodeData"
    ></CDialog>
  </div>
</template>

<script lang="ts">
  interface nodeDataType {
    id: string;
    name: string;
    color: string;
    projectCode: string;
    taskCode: string;
  }
</script>

<script setup lang="ts">
  import { reactive, ref, provide, onMounted } from "vue";
  import CLTable from "@/components/CLTable/index.vue";
  import CToolbar from "@/components/CToolbar.vue";
  import CDialog from "@/components/CDialog.vue";
  import {
    type DynamicField,
    mockCreateFieldsLifecycleStatus,
    mockFieldsLifecycleStatus,
  } from "@/data/wbsFields.ts";
  import { ElMessageBox, ElMessage, ElInput } from "element-plus";
  import {
    type LifeGlobalStatus,
    type queryPagesType,
    type Value,
  } from "@/interface/lifecycle.ts";
  import {
    createLifeGlobalStatus,
    listLifeGlobalStatus,
    getLifecycleFieldList,
    deleteLifeGlobalStatus,
    editLifeGlobalStatus,
    deleteLifeGlobalStatusBatch,
  } from "@/api/lifeCycle.ts";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import { Search } from "@element-plus/icons-vue";

  // 工具栏选项
  const toolbarOptions = ref({
    add: {
      name: "新增",
      enable: true,
    },
    search: false,
    fieldConfig: false,
    filter: false,
    sort: false,
    lineHeight: false,
    help: false,
    log: false,
    export: false,
  });
  const fields = ref<DynamicField[]>([]);
  const searchName = ref("");
  // 字段配置弹窗相关状态
  const showFieldConfig = ref(false);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const currentFields = ref<DynamicField[]>([]);
  const loading = ref<boolean>(false);
  const tableData = ref<LifeGlobalStatus[]>([]);
  const selectedNodes = ref<LifeGlobalStatus[]>([]);
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );
  const moreActions = ref([
    { key: "edit", label: "编辑" },
    { key: "delete", label: "删除" },
  ]);
  const tableConfig = ref({
    editable: false,
    borderMode: "none",
    tableH: "calc(100vh - 175px)",
    // showOperationsColumn: true, // 是否显示操作列
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    OperationsColumnWidth: "60px", //自定义操作列宽度
    frozenColCount: 0, // 冻结前面列数
    rightFrozenColCount: 0, // 冻结后面列数
    page: {
      enable: true,
      totals: 0,
    },
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    // rowSeriesNumber: {
    //   dragOrder: true, // 开启行号拖拽排序
    // },
    // borderMode: "none", // 表格边框模式，none为无边框
  });
  const tableListQuery = reactive<queryPagesType>({
    pageNo: 1,
    pageSize: 10,
    sortParams: [],
    conditions: [],
    logic: "",
    total: 0,
  }); // table列表请求参数
  const operate = ref<string>("create");
  const dialogVisible = ref<boolean>(false);
  const dialogFields = ref<DynamicField[]>([]);
  const fieldsList = ref<Value[]>([]);
  const selectedNode = ref({});
  const nodeData = ref<nodeDataType>({} as nodeDataType);

  const showCLBatchOpToolbar = ref(false);
  const selectedRecords = ref<LifeGlobalStatus[]>([]);
  // dialogFields.value = mockCreateFieldsLifecycleStatus;

  const getFields = async () => {
    fields.value = mockFieldsLifecycleStatus;
    await getLifecycleField();
    dialogFields.value = mockCreateFieldsLifecycleStatus.map((item) => {
      if (item.field === "code") {
        item.options = fieldsList.value.map((item) => {
          return {
            label: item.displayName,
            value: item.code,
          };
        });
      }
      return item;
    });
    console.log(fieldsList.value, "fieldsList");
  };
  // 处理节点选择事件
  const handleNodeSelected = (nodes: LifeGlobalStatus[]) => {
    selectedNodes.value = nodes;
    console.log("handleNodeSelected", nodes);
  };

  // 处理筛选事件
  const handleFilter = (condition: string, direction: "asc" | "desc") => {
    console.log("筛选条件:", condition, "排序方向:", direction);
  };
  // 处理搜索事件
  const handleSearch = () => {
    tableListQuery.conditions.push({
      field: "name",
      operator: "like",
      value: searchName.value,
    });
    getTableList();
  };
  const handleAddLifecycleStatus = () => {
    operate.value = "create";
    dialogVisible.value = true;
  };
  const handleMoreAction = (action: string, node: LifeGlobalStatus) => {
    // const node = deepCopy<LifeGlobalStatus>(tableData.value[index - 1]);
    // console.log("handleMoreAction", action, node);
    if (action === "edit") {
      selectedNode.value = node;
      nodeData.value.projectCode = node.projectCode?.code || "";
      nodeData.value.taskCode = node.taskCode?.code || "";
      nodeData.value.code = node.code?.code || "";
      nodeData.value.id = node.id || "";
      nodeData.value.color = node.color || "";
      nodeData.value.name = node?.statusName || "";
      dialogVisible.value = true;
      operate.value = "edit";
    } else if (action === "delete") {
      ElMessageBox.confirm("确定删除该类型?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      })
        .then(async () => {
          await deleteLifeGlobalStatus(node.id!);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getTableList();
        })
        .catch(() => {});
    } else if (action === "paginationSizeChange") {
    } else if (action === "paginationCurrentChange") {
    }
  };
  const pagerChange = (pager: { currentPage: number; pageSize: number }) => {
    tableListQuery.pageSize = pager.pageSize;
    tableListQuery.pageNo = pager.currentPage;
    getTableList();
  };

  // 处理批量删除操作
  const handleBatchDelete = () => {
    console.log("selectedRecords", selectedRecords.value);
    if (selectedRecords.value.length === 0) return;
    ElMessageBox.confirm("确定删除该生命周期?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true,
    })
      .then(async () => {
        // deleteLifecycleAction(node.id!);
        const ids = selectedRecords.value.map((i) => i.id);
        await deleteLifeGlobalStatusBatch(ids);
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getTableList();
        selectedRecords.value = [];
        showCLBatchOpToolbar.value = false;
      })
      .catch(() => {});
    // 删除完成后清空选中状态
  };

  const handleShowRecords = (records: LifeGlobalStatus[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
  };
  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    console.log(position, "position");
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  provide("showFieldConfigPopup", showFieldConfigPopup);

  const getTableList = async () => {
    loading.value = true;
    const res = await listLifeGlobalStatus(tableListQuery);
    tableListQuery.total = res.total || 0;
    if (res.result && res.result.length) {
      tableData.value =
        res.result.map((item) => {
          item.statusName = item?.name?.zh_CN;
          item.codeName = item?.code?.name?.zh_CN;
          return item;
        }) || [];
    } else {
      tableData.value = [];
    }
    tableListQuery.conditions = [];
    loading.value = false;
  };
  const handleCreateOrEdit = async (formData: Record<string, any>) => {
    console.log("formData", formData);
    let codeName: string = "";
    codeName =
      fieldsList.value.find((item) => item.code === formData.code)
        ?.displayName || "";
    const params: LifeGlobalStatus = {
      id: formData.id,
      icon: formData.icon,
      code: {
        name: {
          zh_CN: codeName,
        },
        code: formData.code,
      },
      name: {
        zh_CN: formData.name,
        en_US: "test test",
      },
      color: formData.color,
    };
    if (operate.value === "create") {
      await createLifeGlobalStatus(params);
      ElMessage({
        type: "success",
        message: "新建成功",
      });
      dialogVisible.value = false;
      getTableList();
    } else if (operate.value === "edit") {
      await editLifeGlobalStatus(params);
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      dialogVisible.value = false;
      getTableList();
    }
  };
  const getLifecycleField = async () => {
    const res = await getLifecycleFieldList();
    // console.log(res.find((item) => item.code === "status"));
    fieldsList.value = res.find((item) => item.code === "STATUS")?.values || [];
    console.log(fieldsList.value, "fieldsList.value");
  };
  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  onMounted(() => {
    getFields();
    getTableList();
  });
</script>

<style scoped lang="scss"></style>
<style scoped>
  .wbs-container {
    background-color: #ffffff;
  }

  .wbs-tree-container {
    background-color: #fff;
    position: relative;
  }

  .batch-btn {
    padding: 4px 12px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 12px;
    color: #42464e;
  }

  .batch-btn:hover {
    color: #42464e;
    background-color: rgba(31, 35, 41, 0.1);
  }

  /* 滚动条样式 */
  .wbs-tree-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .wbs-tree-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb:hover {
    background: #555;
  }
</style>
